package com.one.listener;

import com.one.pojo.OneUser;
import com.one.service.LandService;
import com.one.service.OneUserService;
import com.one.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Description 拆分鸡蛋定时器任务
 * @Author semstouch
 * @Date 2017/4/11
 **/
@Component
public class JobListerner implements ApplicationContextAware,ServletContextAware {
    protected static final Logger logger = LoggerFactory.getLogger(JobListerner.class);
    @Resource
    private LandService landService;
    @Resource
    private OneUserService oneUserService;

    private ApplicationContext applicationContext;
    private ServletContext servletContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    @Scheduled(cron = "0 05 00 * * ?")
    public void run(){
        logger.error("进入拆分鸡蛋时刻!当前时间为"+StringUtils.getStringToday());
        List<OneUser> oneUserList = oneUserService.findAll();
        BigDecimal ratio = new BigDecimal(500.0);
        BigDecimal totalMoney  =oneUserService.totalMoney();
        BigDecimal prveMoney  = oneUserService.previousMoney(StringUtils.yesterdayStartTime().toString(),StringUtils.yesterdayEndTime().toString());
        BigDecimal pubRate  =new BigDecimal(0);
        if(totalMoney!=null&&prveMoney!=null){
            pubRate =prveMoney.divide(totalMoney).multiply(new BigDecimal(100));
            pubRate =pubRate.multiply(ratio);
        }
        if(pubRate.compareTo(new BigDecimal(0.5))==-1){
            pubRate  =new BigDecimal(0.5);
        }
        if(pubRate.compareTo(new BigDecimal(5))==1){
            pubRate  =new BigDecimal(5);
        }
        if(oneUserList!=null){
            for(int i=0;i<oneUserList.size();i++){
               landService.dailyLand(oneUserList.get(i),pubRate,ratio);
            }
        }

    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext=servletContext;
    }
}
